﻿using IRepository.Core;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Transactions;

namespace EntityFrameworks.Data.Core
{
    /// <summary>
    /// Author:zhang.zhanling
    /// 同步文章：http://www.cnblogs.com/lori/p/3455393.html
    /// 对TransactionScope，让它对同一个数据库不产生msdtc服务
    /// 环境：sql2005,sql2008本身已经解决了这个问题
    /// </summary>
    public class TransactionScopeNoMsdtc
    {
        /// <summary>
        /// 产生包裹事务
        /// </summary>
        /// <param name="db">数据上下文</param>
        /// <param name="isOutest">是否为最外层，默认为false</param>
        /// <param name="action">处理代码块</param>
        public static void UsingNoMsdtc(IUnitOfWork db, bool isOutest, Action action)
        {
            var objectContext = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)db).ObjectContext;
            try
            {
                if (objectContext.Connection.State == System.Data.ConnectionState.Closed)
                    objectContext.Connection.Open();

                using (TransactionScope trans = new TransactionScope())
                {
                    action();
                    trans.Complete();
                }
            }
            finally
            {
                if (isOutest)//如果是最外层事务，再将连接关闭！内部事务与外部事务需要共用一个Connection的连接
                    objectContext.Connection.Close();
            }
        }
        /// <summary>
        /// 产生包裹事务，它不是最外层的，如果是最外层的需要调用其它重载
        /// </summary>
        /// <param name="db"></param>
        /// <param name="action"></param>
        public static void UsingNoMsdtc(IUnitOfWork db, Action action)
        {
            UsingNoMsdtc(db, false, action);
        }
    }
}
